package com.zretc.auth.service;

import com.zretc.api.pojo.SysUser;
import com.zretc.auth.dao.SysUserMapper;
import com.zretc.common.constant.SecurityConstant;
import com.zretc.common.constant.WebConstant;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import com.zretc.common.util.JwtUtil;
import com.zretc.redis.service.RedisService;
import com.zretc.security.entity.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    RedisService redisService;

    public RespResult login( SysUser user){
        SysUser srcUser = sysUserMapper.getUserByName(user.getUsername());
        //验证用户名
        if(Objects.isNull(srcUser)){
           return R.fail(WebConstant.LOGIN_ERROR_CODE,WebConstant.ERROR_408);
        }
        //验证密码
        if(!new BCryptPasswordEncoder().matches(user.getPassword(),srcUser.getPassword())){
            return R.fail(WebConstant.LOGIN_ERROR_CODE,WebConstant.ERROR_408);
        }

        //如果登录成功- 直接查询权限列表
        ArrayList<String> roleList = sysUserMapper.getRoleList(srcUser.getId());
        //封装权限模型
        LoginUser loginUser = new LoginUser(srcUser, roleList, null);
        //根据userId生成JWT字符串
        String token = JwtUtil.createJWT(String.valueOf(srcUser.getId()));
        //存储登录信息到redis
        redisService.setCacheObject("login:" + srcUser.getId(),loginUser);

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put(SecurityConstant.AUTHENTICATION_HEADER_NAME,token);
        //如果有必要 同时相应用户名和头像等操作  srcUser

        return R.success(resultMap);


    }
}
